package com.alks.function.controller.task;


import com.alks.common.aop.RedisLock;
import com.alks.common.data.dto.SysUserTokenDTO;
import com.alks.common.service.RedisService;
import com.alks.common.utils.JWTUtil;
import com.alks.common.utils.MD5Utils;
import com.alks.common.utils.beanutils.BeanUtil;
import com.alks.entity.data.entity.SdPrgPrivilege;
import com.alks.entity.data.entity.SdUser;
import com.alks.entity.data.enums.ResultCodeEnum;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.function.data.dto.sys.SdUserDto;
import com.alks.function.data.request.sys.SysUserRequest;
import com.alks.function.mapper.SdUserMapper;
import com.alks.function.mapper.system.SYS_SdPrgPrivilegeMapper;
import com.alks.function.mapper.system.SYS_SdProgramMapper;
import com.alks.function.service.impl.SysUserServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import static com.alks.entity.data.enums.ResultCodeEnum.LOGIN_ERROR;

/**
 * 定时登录
 * 实现pda不用token
 */
@Component
@Slf4j
@EnableScheduling
@EnableAsync
public class LoginTask {

    @Autowired
    private RedisService redisService;
    @Resource
    private SYS_SdPrgPrivilegeMapper privilegeMapper;
    @Resource
    private SdUserMapper sdUserMapper;


    @Resource
    private SysUserServiceImpl sysUserService;


    /**
     * 每天定时登录：LTF和pda001
     */
    @Async("TaskExecutor")
    @Scheduled(cron = "0 0,30 6-8,12,19-22 * * ?") //  每天6点，7点，8点，(6.30,7.30,8.30)12点，19,20,21,22点执行一次
    @Transactional
    @RedisLock(key = "task:LoginTask.ScheduleInsertPcStitchStatus")
    public void ScheduleInsertPcStitchStatus(){
        try{
            log.info("定时任务执行开始,登录：");

            SysUserRequest userRequest1 = new SysUserRequest();
            userRequest1.setLoginName("LTF");
            userRequest1.setPassword("kl@123111");
            this.login(userRequest1);

            SysUserRequest userRequest2 = new SysUserRequest();
            userRequest2.setLoginName("PDA001");
            userRequest2.setPassword("PDA001@1");
            this.login(userRequest2);

            log.info("定时任务执行成功, ‘LTF/PDA001 登录成功！");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public ResponseInfo login(SysUserRequest sysUser){
        if (sysUser == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (BeanUtil.allIsEmpty(sysUser.getPassword()) || BeanUtil.allIsEmpty(sysUser.getLoginName())) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        String username = sysUser.getLoginName().toUpperCase();
        //SdUser baseSysUser = lambdaQuery().eq(SdUser::getEngName, username).one();
        SdUser baseSysUser = sdUserMapper.getUser3(username);

        //根据用户名获取用户数据
        if (baseSysUser == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_USERNAME_NOT_EXIST.getMessage(), ResultCodeEnum.LOGIN_USERNAME_NOT_EXIST.getCode());
        }
        //在职且状态正常
        if ("Y".equals(baseSysUser.getLockStatus())) {
            return ResponseInfo.error("账号已锁定", LOGIN_ERROR.getCode());
        }
        /*密码验证部分*/
        String salt = baseSysUser.getSalt();
        String basePwd = baseSysUser.getPassword();
        String password = sysUser.getPassword() + salt;
        password = MD5Utils.md5(password);
        log.info(password);
        //判断密码是否正确
        if (BeanUtil.allIsEmpty(password) || !basePwd.equals(password)) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_PASSWORD_ERROR.getMessage(), ResultCodeEnum.LOGIN_PASSWORD_ERROR.getCode());
        }
        //记录用户登录的时间
        Date currentTime = new Date();
        baseSysUser.setLastLogin(currentTime);

        /*根据角色获取权限ID*/
        LambdaQueryWrapper<SdPrgPrivilege> privilegeWrapper = new LambdaQueryWrapper<SdPrgPrivilege>()
                .eq(SdPrgPrivilege::getPosId, baseSysUser.getPosId());
        List<String> prgId = privilegeMapper.selectList(privilegeWrapper).stream()
                .map(SdPrgPrivilege::getPrgId).collect(Collectors.toList());
        //复制 sysUserVo 信息到 sysUserTokenDto
        SysUserTokenDTO dto = new SysUserTokenDTO();
        BeanUtils.copyProperties(baseSysUser, dto);
        dto.setDeptId(baseSysUser.getDeptNo());
        dto.setUserName(baseSysUser.getChiName());
        dto.setLoginName(baseSysUser.getEngName());
        dto.setRole(baseSysUser.getPosId());
        dto.setPrgIds(prgId);
        // 添加用户权限
        String token = JWTUtil.generateToken(dto);
        String role = dto.getRole();
        String key = baseSysUser.getUserId() + "_" + "token";
        if (BeanUtil.allIsEmpty(role)) {
            key = key + "_" + dto.getRole();
        }
        //MS TODO 2024/7/26 : 对TK进行分类存储
        redisService.set(key, token);
        sysUserService.updateById(baseSysUser);
        SdUserDto user2 = sdUserMapper.getUser2(baseSysUser.getUserId(), baseSysUser.getCompanyId());
        HashMap<String, Object> map = new HashMap<>();
        /*获取权限信息*/
        map.put("Authorization", key);
        map.put("name", baseSysUser.getChiName());
        map.put("userInfo", user2);
        return ResponseInfo.ok(map);
    }

}
